package com.wisenet.controller.client.wxpubno;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wisenet.annotation.LoginValidate;
import com.wisenet.cache.SimpleCacheProvider;
import com.wisenet.common.Const;
import com.wisenet.common.WxConst;
import com.wisenet.controller.PlatformController;
import com.wisenet.entity.WeixinPubno;
import com.wisenet.service.wxpubno.EventService;
import com.wisenet.service.wxpubno.FzhService;
import com.wisenet.service.wxpubno.WeixinService;
import com.wisenet.wx.util.MessageUtil;
import com.wisenet.wx.util.SignUtil;
import com.wisenet.wx.util.StringUtil;

/**
 * 核心请求处理类
 * @author fzh
 */
@Controller
public class FzhController extends PlatformController {
	@Autowired
	private FzhService fzhService;
	@Autowired
	private EventService eventService;
	@Autowired
	private WeixinService weixinService;
	@Autowired
	private SimpleCacheProvider cacheProvider;
	
	public static Logger logger = Logger.getLogger(FzhController.class);

	/**
	 * 确认请求来自微信服务器
	 * @param request
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/fzhwx", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
	public @ResponseBody String doGet(HttpServletRequest request) {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
		boolean flag = SignUtil.checkSignature(signature, timestamp, nonce, "fzh2017");
		return flag ? echostr : null;
	}

	/**
	 * 处理微信服务器发来的消息
	 * @param request
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/fzhwx", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	public @ResponseBody String doPost(HttpServletRequest request) {
		String msgType = null, toUserName = null, fromUserName = null;
		try {
			// 解析微信发来的请求(xml)
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			toUserName = requestMap.get(WxConst.TO_USER_NAME);
			fromUserName = requestMap.get(WxConst.FROM_USER_NAME);
			msgType = requestMap.get(MessageUtil.MESSAGE_TYPE);

			// 事件推送
			if (MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) {
				return eventService.operateEventMessage(requestMap);
			}
			
			// 获取账号信息
			WeixinPubno pubno = cacheProvider.get("");
			if (pubno == null) {
				logger.error("APP不存在");
				return SUCCESS;
			}
			
			String wxToken = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
			if (wxToken == null) {
				logger.error("TOKEN不存在");
				return SUCCESS;
			}
			
			// 处理文本输入回复消息
			if (MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType)) {
				// 设置wxToken
				requestMap.put(WxConst.WX_TOKEN, wxToken);
				
				// 06重新猜数
				if (Const.GUESS_NUMBER_INPUT.equals(requestMap.get(WxConst.CONTENT))) {
					requestMap.put(MessageUtil.EVENT_KEY, Const.MENU_TYPE_GUESS_NUMBER);
					return eventService.replyMessageByClickMenu(requestMap);
				}
				
				// 根据输入回复消息
				String result = fzhService.operateTextMessage(requestMap);
				return result == null ? SUCCESS : result;
			}
			// 图片消息
			else if (MessageUtil.REQ_MESSAGE_TYPE_IMAGE.equals(msgType)) {
				return SUCCESS;
			}
			// 音频消息
			else if (MessageUtil.REQ_MESSAGE_TYPE_VOICE.equals(msgType)) {
				return fzhService.operateVoiceMessage(requestMap);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return SUCCESS;
		}
		return MessageUtil.replyTextMessage(fromUserName, toUserName, StringUtil.strContent());
	}
	
	@Override
	protected String getBasePath() {
		return null;
	}

}
